<template>
  <div>
    <van-form @submit="saveContact">
      <van-nav-bar
        title="编辑联系人"
        left-text="返回"
        left-arrow
        @click-left="goBack"
      />
      <van-field
        v-model="contact.name"
        label="姓名"
        placeholder="请输入姓名"
        required
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="contact.phoneNum"
        label="电话"
        placeholder="请输入电话"
        required
        :rules="[
          { required: true, message: '请填写电话号码' },
          { validator: validatePhone, message: '电话号码格式不正确' },
        ]"
      />
      <van-field
        v-model="contact.email"
        label="邮箱"
        placeholder="请输入邮箱"
        required
        :rules="[
          { required: true, message: '请填写邮箱' },
          { validator: validateEmail, message: '邮箱格式不正确' },
        ]"
      />
      <van-cell class="switch-label" center title="是否设置为默认联系人">
        <template #right-icon>
          <van-switch v-model="contact.def" size="24px" />
        </template>
      </van-cell>
      <div class="button-container">
        <van-button
          class="contain-btn"
          type="primary"
          round
          native-type="submit"
          >保存</van-button
        >
        <van-button
          class="contain-btn"
          type="danger"
          round
          @click="confirmDelete"
          >删除</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
/* eslint-disable */
import { send_email } from "@/api/index";
import {
  recommend_add,
  recommend_page,
  recommend_update,
  recommend_delete,
} from "@/api/index";
import { getLocal } from "@/utils/index";
import { Toast } from "vant";
import cloneDeep from "lodash/cloneDeep";
export default {
  data() {
    return {
      contact: {
        id: "",
        name: "",
        phoneNum: "",
        email: "",
        def: false,
      },
      isSend: false,
    };
  },
  methods: {
    async saveContact() {
      const visitorData = getLocal("visitorData");
      const payload = {
        ...this.contact,
        visitorId: visitorData.id,
        visitorName: visitorData.name,
      };
      const res = await recommend_update(payload);
      if (res.code == 0) {
        // 若设置默认联系人，则将原有的默认联系人设置为false
        if (this.contact.def === true) {
          const res2 = await recommend_page({
            visitorId: visitorData.id,
            def: true,
          });
          // const rid = res2.data.list.length > 1 ? res2.data.list[0].id : null;
          const myItem = res2.data.list.filter(
            (item) => item.id != this.contact.id
          );
          const rid = myItem.length > 0 ? myItem[0].id : null;
          console.log("rid", rid);
          if (rid) {
            const res3 = await recommend_update({
              id: rid,
              def: false,
            });
          }
        }
        console.log(111);
        this.contact = {
          name: "",
          phoneNum: "",
          email: "",
          def: false,
        };
        this.isSend = false;
        this.$router.push("/recommend");
        return Toast.success("修改成功!");
      } else {
        return Toast.fail(res.msg);
      }
    },
    goBack() {
      this.$router.push('recommend');
    },
    validatePhone(value) {
      return /^1[3|4|5|7|8][0-9]\d{8}$/.test(value);
    },
    validateEmail(value) {
      return /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(
        value
      );
    },
    confirmDelete(e) {
      e.preventDefault();
      this.$dialog
        .confirm({
          title: "提示",
          message: "确定要删除该联系人吗？",
        })
        .then(() => {
          this.deleteContact();
        })
        .catch(() => {
          console.log("取消删除");
        });
    },
    async deleteContact() {
      const payload = [this.contact.id];
      const res = await recommend_delete(payload);
      if (res.code == 0) {
        this.$router.push("/recommend");
        return Toast.success("删除成功");
      } else {
        return Toast.fail(res.msg);
      }
    },
  },
  watch: {
    $route(to, from) {
      // console.log("路由发生了变化：", to);
      this.contact = cloneDeep(to.query);
      this.contact.def = this.contact.def === "true" ? true : false;
      // console.log(this.contact);
    },
  },
  created() {
    console.log("created");
    this.contact = this.$route.query;
    this.contact.def = this.contact.def === "true" ? true : false;
  },
};
</script>

<style lang="less" scoped>
.switch-label {
  color: #646566;
}

.button-container {
  display: flex;
  flex-direction: column;
  margin-top: 20px;

  .contain-btn {
    margin: 0.5vh 3vh;
  }
}
</style>
